﻿using System.Xml;
using Md.Api.Model.Util.Xml.Request;
using Newtonsoft.Json;

namespace Md.Util.Service.Xml;
/// <summary>
/// XML节点属性修改服务
/// </summary>
public class UpdateXmlNodeAttributeService : ApiBase<RequestUpdateXmlNodeAttributeModel>
{
    /// <summary>
    /// 执行
    /// </summary>
    protected override void ExecuteMethod()
    {
        if (string.IsNullOrWhiteSpace(Parameter.xmlFilePath))
        {
            throw new AggregateException("xml文件路径不能为空");
        }

        if (string.IsNullOrWhiteSpace(Parameter.xmlNode))
        {
            throw new AggregateException("xml节点不能为空");
        }

        if (Parameter.xmlNodeAttributeJSONStrList == null)
        {
            throw new AggregateException("xml节点属性不能为空");
        }

        XmlDocument xmlDoc = new XmlDocument();

        xmlDoc.Load(Parameter.xmlFilePath);

        var xmlNode = xmlDoc.SelectSingleNode(Parameter.xmlNode) as XmlElement;

        var attributeList = JsonConvert.DeserializeObject<List<XmlNodeAttributeModel>>(Parameter.xmlNodeAttributeJSONStrList);

        if (xmlNode != null && attributeList != null && attributeList.Count() > 0)
        {
            foreach (var attribute in attributeList)
            {
                xmlNode.SetAttribute(attribute.attributeName, attribute.attributeValue);
            }

            xmlDoc.Save(Parameter.xmlFilePath);

            Result.Data = Parameter.xmlFilePath;
            Result.Msg = "success";
        }
        else
        {
            throw new AggregateException("xml节点属性更新失败");
        }
    }
}

/// <summary>
/// XML节点属性实体
/// </summary>
public class XmlNodeAttributeModel
{
    /// <summary>
    /// 属性名称
    /// </summary>
    public string attributeName { get; set; } = string.Empty;
    /// <summary>
    /// 属性值
    /// </summary>
    public string attributeValue { get; set; } = string.Empty;
}
